<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<style type="text/css">
			#box {
				height: 200px;
				width: 100%;
				text-align: center;
			}
			
			.loading {
				display: flex;
				justify-content: center;
			}
	
			.loading div{
				width:30px;
				height:100px; 
				margin:15px;
				background-color:gold;
				border-radius:15px;
				animation:loading 500ms ease infinite alternate;
			}
			
			.loading div:nth-child(1){
				background-color:red;
			}
			
			.loading div:nth-child(2){
				background-color:green;
				animation-delay:100ms;
			}
			
			.loading div:nth-child(3){
				background-color:pink;
				animation-delay:200ms;
			}
	
			.loading div:nth-child(4){
				background-color:lightgreen;
				animation-delay:300ms;
			}
	
			.loading div:nth-child(5){
				background-color:lightblue;
				animation-delay:400ms;
			}
	
			@keyframes loading{         
				from{
					transform:scale(1,1);
				}
				to{
					transform:scale(1,0.5);
				}
			}
			
			textarea {
				border: 0;
				resize: none;
			}
			
			.btn-list {
				position: fixed;
				bottom: 10px;
				width: calc(100% - 16px);
				display: flex;
			}
			
			.btn {
				flex: 1;
				margin: 0 10px;
				font-size: 16px;
				background-color: #1E90E6;
				border: 0;
				color: #ffffff;
				height: 40px;
			}
		</style>
		<script src='./tinymce/tinymce.min.js'></script>
		<!-- <script src='./tinymce/themes/mobile/theme.min.js'></script> -->
		<script type="text/javascript" src="./tinymce/jquery.min.js"></script>
		<script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.1/index.js"></script>
	</head>

	<body>
		<div id="box">
			<div class="loading">
				<div></div>
				<div></div>
				<div></div>
				<div></div>
				<div></div>
			</div>
			<div>Loading...</div>
		</div>

		<div id="content" style="display: none;">
			<form method="post">
				<textarea id="mytextarea"></textarea>
			</form>
			
			<div class="btn-list" style="display: none;">
				<button class="btn" type="button" data-action="save">保存</button>
				<button class="btn" type="button" data-action="confirm">确定</button>
				<button class="btn" type="button" data-action="cancel">取消</button>
			</div>
		</div>
		
		<script type="text/javascript">
			console.log("进入页面：", new Date().getTime());
			// 取url中的参数值
			function getQuery(name) {
				// 正则：[找寻'&' + 'url参数名字' = '值' + '&']（'&'可以不存在）
				let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
				let r = window.location.search.substr(1).match(reg);
				if(r != null) {
					// 对参数值进行解码
					return decodeURIComponent(r[2]);
				}
				return null;
			}
			var fileObj = JSON.parse(getQuery('fileObj'))
			var type = getQuery('type')
			// if(type == 'edit') {
			// 	$('.btn-list')[0].removeAttribute('style', 'display: none;')
			// }
			
			console.log("开始初始化：", new Date().getTime());
			// 初始化
			tinymce.init({
				selector: '#mytextarea',
				readonly: type == 'view' ? true : false,
				// mobile: {
				// 	menubar: false,
				// 	toolbar_mode: 'floating'
				// },
				menubar: false,
				language: 'zh_CN',
				min_height: type == 'view' ? window.screen.availHeight - 150 : window.screen.availHeight - 180,
				max_height: type == 'view' ? window.screen.availHeight - 150 : window.screen.availHeight - 180,
				statusbar: false,
				plugins: 'preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr nonbreaking insertdatetime advlist lists wordcount imagetools textpattern autosave autoresize',
				toolbar: 'alignleft aligncenter alignright alignjustify outdent indent formatpainter bullist numlist | forecolor backcolor bold italic underline strikethrough charmap styleselect formatselect fontselect fontsizeselect',
				fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
				font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
				branding: false
			});
			console.log("初始化完成：", new Date().getTime());
			
			console.log("开始获取数据：", new Date().getTime());
			// 获取文件
			$.ajax({
				url: fileObj.baseUrl + '/extend/v3/DocumentCollection/getFileByCollId',
				type: "GET",
				data: { collectionId: fileObj.collectionId },
				success: function(res) {
					if (res.data && res.data.length > 0) {
						fileId = res.data[0].fileId
						getContent(fileId)
					} else {
						$("#box")[0].setAttribute('style', 'display: none;')
						$("#content")[0].removeAttribute('style', 'display: none;')
						if(type == 'edit') {
							$('.btn-list')[0].removeAttribute('style', 'display: none;')
						}
					}
				},
				error: function(err) {
					console.log('获取文件失败：' + JSON.stringify(err))
				}
			});
			
			// 获取数据
			function getContent(fileId) {
				$.ajax({
					url: fileObj.baseUrl + '/platform/v3/file/download',
					type: "GET",
					data: { attachmentId: fileId },
					success: function(res) {
						console.log("获取数据完成：", new Date().getTime());
						// 此处加延时，防止初始化过慢，导致赋值失败
						setTimeout(() => {
							tinyMCE.activeEditor.setContent(res)
							$("#box")[0].setAttribute('style', 'display: none;')
							$("#content")[0].removeAttribute('style', 'display: none;')
							if(type == 'edit') {
								$('.btn-list')[0].removeAttribute('style', 'display: none;')
							}
						}, 500)
					},
					error: function(err) {
						console.log('获取数据失败：' + JSON.stringify(err))
					}
				});
			}
			
			// 处理键盘弹起
			var originHeight = document.documentElement.clientHeight || document.body.clientHeight;
			
			const handleResize = () => {
				var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
				if (resizeHeight < originHeight) {
					$('.btn-list')[0].setAttribute('style', 'display: none;')
				} else {
					$('.btn-list')[0].removeAttribute('style', 'display: none;')
				}
			}
			
			window.addEventListener('resize', handleResize);
			
			document.addEventListener('UniAppJSBridgeReady', function() {
				document.querySelector('.btn-list').addEventListener('click', async function(evt) {
					var target = evt.target;
					if (target.tagName === 'BUTTON') {
						var action = target.getAttribute('data-action');
						if(action == 'cancel') {
							uni.navigateBack()
						} else {
							// 文件转换
							const transToFile = async(blob, fileName, fileType) => {
								return new window.File([blob], fileName, { type: fileType })
							}
							// 生成文件
							var data = tinyMCE.activeEditor.getContent()
							let blob = new Blob([data], { type: 'text/plain;charset=utf-8' })
							let fileName = fileObj.fileName ? fileObj.fileName + '.html' : new Date().getTime() + '.html'
							let textContain = await transToFile(blob, fileName, 'text/plain')
							
							var formData = new FormData()
							formData.append('file', textContain)
							formData.append('collectionId', fileObj.collectionId)
							formData.append('businessCode', fileObj.businessCode)
							formData.append('subBusinessCode', fileObj.subBusinessCode)
							formData.append('businessDataCode', fileObj.businessDataCode)
							formData.append('fileSum', 1)
							formData.append('userName', fileObj.userName)
							
							let ret = {}
							$.ajax({
								url: fileObj.baseUrl + '/extend/v3/DocumentCollection',
								type: "POST",
								data: formData,
								processData: false,
								contentType: false,
								success: function(data) {
									if(data.data) {
										ret = {
											flag: true,
											msg: '',
											action: action
										}
									} else {
										ret = {
											flag: false,
											msg: data.message,
											action: action
										}
									}
								},
								error: function(err) {
									console.log('上传失败：' + JSON.stringify(err))
									ret = {
										flag: false,
										msg: err.cause,
										action: action
									}
								}
							});
							
							setTimeout(() => {
								uni.postMessage({
									data: {
										data: ret
									}
								})
								if(action == 'confirm') {
									uni.navigateBack()
								}
							}, 500)
						}
					}
				});
			});
		</script>
	</body>
</html>